<script setup>
import {ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {login} from '@/api/user'
import {setToken} from '@/utils/auth'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const form = ref({
	username: '',
	password: ''
})

const loading = ref(false)
const loginRules = {
	username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
	password: [{required: true, message: '请输入密码', trigger: 'blur'}]
}

const handleLogin = async () => {
	loading.value = true
	try {
		const res = await login(form.value)
		if (res.code == 200) {
			ElMessage.success('登录成功')
			setToken(res.token)
			userStore.setUser(res.user) // 存储用户信息到Pinia
			router.replace('/')
		}
	} catch (error) {
		ElMessage.error(error.response?.data?.message)
	} finally {
		loading.value = false
	}
}
</script>

<template>
	<div class="login-container">
		<el-card class="login-card">
			<h2 class="login-title">手工艺品知识图谱系统</h2>
			<el-form
				:model="form"
				:rules="loginRules"
				label-width="80px"
				@submit.prevent="handleLogin"
			>
				<el-form-item label="用户名" prop="username">
					<el-input
						v-model="form.username"
						placeholder="请输入用户名"
						clearable
					/>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input
						v-model="form.password"
						type="password"
						placeholder="请输入密码"
						show-password
						clearable
						@keyup.enter="handleLogin"
					/>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						@click="handleLogin"
						:loading="loading"
					>
						登录
					</el-button>
					<el-button @click="router.push('/regis')">没有账号？去注册</el-button>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<style scoped>
.login-container {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	background: url('@/assets/login-bg.jpg') no-repeat center center;
	background-size: cover;
}

.login-card {
	width: 450px;
	padding: 30px;
	border-radius: 10px;
	box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}

.login-title {
	text-align: center;
	margin-bottom: 30px;
	color: #409eff;
	font-size: 24px;
	font-weight: bold;
}
</style>
